<template>
  <div class="hello" width="100%" height="100%">

    <baidu-map class="map"
               :center="{lng: 116.404, lat: 39.915}"
               :zoom="14"
               @mousemove="syncPolyline"
               @click="paintPolyline"
               @rightclick="newPolyline">
      <bm-control>
        <button @click="toggle('polyline')">{{ polyline.editing ? '停止绘制' : '开始绘制' }}</button>
      </bm-control>

      <bm-polyline :key="path.lon" :path="path"  v-for="path of polyline.paths"></bm-polyline>


    </baidu-map>

  </div>
</template>

<script>
import {
  BmlLushu,
  BaiduMap,
  BmControl,
  BmView,
  BmAutoComplete,
  BmLocalSearch,
  BmMarker,
  BmGeolocation,

} from "vue-baidu-map";

  export default {
    data () {
      return {
        polyline: {
          editing: false,
          paths: [
            [
              {
                  lat: 39.920202,
                  lng: 116.313738,
              },
              {
                lat: 39.921973,
                lng: 116.37626,
              },
              {
                lat: 39.905813,
                lng: 116.390346,
              },
              {
                lat: 39.901606,
                lng: 116.427572,
              },
            ]
          ]
        }
      }
    },
    methods: {
      toggle (name) {
        this[name].editing = !this[name].editing
      },
      syncPolyline (e) {
        if (!this.polyline.editing) {
          return
        }
        const {paths} = this.polyline
        if (!paths.length) {
          return
        }
        const path = paths[paths.length - 1]
        if (!path.length) {
          return
        }
        if (path.length === 1) {
          path.push(e.point)
        }
        this.$set(path, path.length - 1, e.point)
      },
      newPolyline (e) {
        if (!this.polyline.editing) {
          return
        }
        const {paths} = this.polyline
        if(!paths.length) {
          paths.push([])
        }
        const path = paths[paths.length - 1]
        path.pop()
        if (path.length) {
          paths.push([])
        }
      },
      paintPolyline (e) {

        console.log("paintPolyline",this.polyline)

        if (!this.polyline.editing) {
          return
        }
        const {paths} = this.polyline
        !paths.length && paths.push([])
        paths[paths.length - 1].push(e.point)

      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.map {
  width: 100%;
  height: 500px;
}
</style>
